package org.example;

import org.openjdk.jol.info.ClassLayout;

import java.util.ArrayList;
import java.util.List;

public class Main11 {

    /**
     * 批量撤销
     */
    public static void main(String[] args) throws Exception {


        List<A> list = new ArrayList<>();
        //生成40个A的实例
        for (int i = 0; i < 40; i++) {
            list.add(new A());
        }

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                A a = list.get(i);
                synchronized (a) {
                    if (i == 1 || i == 19) {
                        System.out.println("t1 lock " + i);
                        //打印对象头
                        System.out.println(ClassLayout.parseInstance(a).toPrintable());//偏向锁
                    }
                }
            }
        },"线程1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                A a = list.get(i);
                synchronized (a) {
                    if (i == 1 || i == 19 || i == 39) {//i<19的时候轻量锁， i>=19的时候是偏向锁
                        System.out.println("t2 lock " + i);
                        System.out.println(ClassLayout.parseInstance(a).toPrintable());
                    }
                }
            }
        },"线程2");

        Thread t3 = new Thread(() -> {
            for (int i = 19; i < 40; i++) {
                A a = list.get(i);
                synchronized (a) {
                    if (i == 19 || i == 39) {
                        System.out.println("t3 lock " + i);
                        System.out.println(ClassLayout.parseInstance(a).toPrintable()); //线程3后面20个对象从重偏向之后又升级为轻量级锁
                    }
                }
            }
        },"线程3");


        t1.start();
        t1.join();//通过join是t1结束后再启动t2,避免竞争

        t2.start();
        t2.join();

        t3.start();
        t3.join();

        System.out.println("===========");
        System.out.println(ClassLayout.parseInstance(new A()).toPrintable());

    }

}

